import { Component, Input, Output, EventEmitter } from "@angular/core";
import { CriteriaResultModel, CriteriaModel } from "../../models/criteriaResult.model";
import { ReportingService, TargetType } from "../../reporting.service";
import { Observable } from "rxjs";
import { FilterModel, FilterType } from "../../models/filter.model";

@Component({
    selector: 'criteria-listing',
    templateUrl: 'criteriaListing.component.html',
    styleUrls: ['../../reporting.component.scss']
})
export class CriteriaListingComponent {
    public result: CriteriaResultModel;
    public targetType: typeof TargetType = TargetType;
    public filterType: typeof FilterType = FilterType;
    
    private _filter: FilterModel;
    public filterTarget: TargetType;

    public criteriaArray: CriteriaModel[] = [];

    @Input() set filter(value: FilterModel) {
        if (value) {
            this._filter = value;
            this.filterTarget = value.targetType;
            this.getBulkCriteria(true);
        }
    }

    get filter(): FilterModel{
        return this._filter;
    }

    @Output() criteriaChanged: EventEmitter<CriteriaResultModel> = new EventEmitter();

    @Output() add: EventEmitter<void> = new EventEmitter<void>();

    @Output() edit: EventEmitter<string> = new EventEmitter();

    constructor(private toolsService: ReportingService) { }

    public getBulkCriteria(refreshOutputResult: boolean) {
        let call: Observable<CriteriaResultModel> = this.toolsService.getResults(this._filter.id, false, true, 'CompanyNameLowerCase', 0, 1);
        let action: (value: CriteriaResultModel) => void = data => {
            this.result = data;
            if (data) this.criteriaArray = this.result.items[0].criteria;            
            this.criteriaChanged.emit(data);
        }

        if (refreshOutputResult)
            this.toolsService.populateOutputResult(this._filter.id).subscribe(_ => {
                call.subscribe(action);
            });
        else
            call.subscribe(action);
    }

    public allowEdit(criteria): boolean {
        //TODO: also editable if isAdmin interface and targetType != Report
        return criteria.companiesCount != 'Data Point' &&
            this._filter.isCurrentUserOwner &&
            this._filter.type != FilterType.Standard &&
            this._filter.targetType != TargetType.Report;
    }

    public editCriteria(criteriaId: string) {
        this.edit.emit(criteriaId);
    }

    public addCriteria(){
        this.add.emit();
    }

    public deleteCriteriaById(criteriaId: string) {
        this.toolsService.deleteCriteria(this._filter.id, criteriaId).subscribe(_ => {
            this.getBulkCriteria(false);
        });
    }

    public deleteCriteriaByGroup(criteriaId: string, criteriaGroupId: string) {
        this.toolsService.deleteCriteriaGroup(this._filter.id, criteriaId, criteriaGroupId).subscribe(data => {
            this.getBulkCriteria(true);
        })
    }

}